//
//  AppController.m
//  Rainbow
//
//  Created by Alex on 21/07/09.
//  Copyright 2009 Erasmus Software. All rights reserved.
//

#import "AppController.h"
#import "MBPreferencesController.h"
#import "GeneralViewController.h"
#import "MobileMeViewController.h"
#import "XMLInterface.h"
#import "GridViewController.h"
#import "ListViewController.h"


@implementation AppController

+ (void)initialize
{
	NSMutableDictionary *defaultValues = [NSMutableDictionary dictionary];	
	[defaultValues setObject:@"" forKey:ESUserName];
	[defaultValues setObject:@"" forKey:ESUserEmail];
	[[NSUserDefaults standardUserDefaults] registerDefaults:defaultValues];
}

- (void)initSearchBar
{
	// search field option
	NSMenu *cellMenu = [[NSMenu alloc] initWithTitle:@"Search Menu"];
    NSMenuItem *item;
	
	item = [[NSMenuItem alloc] initWithTitle:@"All"
									  action:@selector(setSearchCategoryFrom:)
							   keyEquivalent:@""];
    [item setTarget:self];
    [item setTag:0];
	[cellMenu insertItem:item atIndex:0];
	[item release];
	
    item = [[NSMenuItem alloc] initWithTitle:@"Title"
									  action:@selector(setSearchCategoryFrom:)
							   keyEquivalent:@""];
    [item setTarget:self];
    [item setTag:1];
	[cellMenu insertItem:item atIndex:1];
	[item release];
	
	item = [[NSMenuItem alloc] initWithTitle:@"Director"
									  action:@selector(setSearchCategoryFrom:)
							   keyEquivalent:@""];
    [item setTarget:self];
    [item setTag:2];
	[cellMenu insertItem:item atIndex:2];
	[item release];
	
	item = [[NSMenuItem alloc] initWithTitle:@"Year"
									  action:@selector(setSearchCategoryFrom:)
							   keyEquivalent:@""];
    [item setTarget:self];
    [item setTag:3];
	[cellMenu insertItem:item atIndex:3];	
	[item release];
	item = [[NSMenuItem alloc] initWithTitle:@"Kind"
									  action:@selector(setSearchCategoryFrom:)
							   keyEquivalent:@""];
    [item setTarget:self];
    [item setTag:4];
	[cellMenu insertItem:item atIndex:4];
		
	item = [[NSMenuItem alloc] initWithTitle:@"Summary"
									   action:@selector(setSearchCategoryFrom:)
                                keyEquivalent:@""];

    [item setTarget:self];
    [item setTag:5];
	[cellMenu insertItem:item atIndex:5];
	[item release];
    id searchCell = [search_field cell];
	[searchCell setSearchMenuTemplate:cellMenu];
	[cellMenu release];
}

- (void)awakeFromNib
{
	// Preferences
	GeneralViewController *general = [[GeneralViewController alloc] initWithNibName:@"PreferencesGeneral" bundle:nil];
	MobileMeViewController *mobileMe = [[MobileMeViewController alloc] initWithNibName:@"PreferencesMobileMe" bundle:nil];
	[[MBPreferencesController sharedController] setModules:[NSArray arrayWithObjects:general, mobileMe, nil]];
	[general release];
	[mobileMe release];
	[self initSearchBar];
	tv = [[NSTableView alloc] init];
	tv = [[viewControllers objectAtIndex:1] tableView];
	dvd_list = [[Dvd alloc] init];
	[dvd_list retain];
	[[viewControllers objectAtIndex:0] setDvdList:dvd_list];
	[[[viewControllers objectAtIndex:0] DvdGrid] reloadData];

	[[viewControllers objectAtIndex:1] setDvdList:dvd_list];
	[[viewControllers objectAtIndex:1] setUp:self];
	[[[viewControllers objectAtIndex:1] tableView] reloadData];
	
	ManagingViewController *vc = [viewControllers objectAtIndex:0];
	[self displayViewController:vc];
	[[NSNotificationCenter defaultCenter] postNotificationName:kHelloDataSourceDidChangeNotification object:nil];
}

- (IBAction)setSearchCategoryFrom:(NSMenuItem *)menuItem
{
    searchCategory = [menuItem tag];
    [[search_field cell] setPlaceholderString:[menuItem title]];
}

- (id) init 
{
	self = [super init];
	if (self != nil)
	{
		//Notification declaration
		[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(dataSourceDidChange:) name:kHelloDataSourceDidChangeNotification object:nil];
		[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(gridSelectionDidChange:) name:kGridSelectionDidChange object:nil];
		[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(gridNoSelection:) name:kNoSelection object:nil];	
		[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(tableViewSelection:) name:kSelectionDidChange object:nil];		

		amazonPanel = [[AmazonCall alloc] init];
		//multi view definition
		viewControllers = [[NSMutableArray alloc] init];
		ManagingViewController	*vc;
		vc = [[GridViewController alloc] init];
		[vc setManagedObjectContext:[self managedObjectContext]];
		[viewControllers addObject:vc];
		[vc release];
		vc = [[ListViewController alloc] init];
		[vc  setManagedObjectContext:[self managedObjectContext]];
		[viewControllers addObject:vc];
		[vc release];
		
		// Search Category init
		searchCategory = 0;
	}
	return self;
}

- (int) numberOfRowsInTableView:(NSTableView *)tv
{
	return [dvd_list count];
}

- (id) tableView:(NSTableView *)tv objectValueForTableColumn:(NSTableColumn *)tableColumn row:(int)row
{
	NSDictionary *item = [NSDictionary alloc];
	
	item = [dvd_list itemAtIndex:row];
	if (YES == [[tableColumn identifier] isEqualToString:kTitle])
		return [item objectForKey:kTitle];
	else if (YES == [[tableColumn identifier] isEqualToString:kDirector])
		return [item objectForKey:kDirector];
	else if (YES == [[tableColumn identifier] isEqualToString:kYear])
		return [item objectForKey:kYear];
	return nil;
}

- (IBAction) addItem:(id) sender
{	
	AmazonModule *amazon = [[AmazonModule alloc] initWithStrTitle:[title_add stringValue]];

	[dvd_list addDvdWithTitle:[title_add stringValue] director:[amazon getDirectors]
						 year:[amazon getYear] language:@"" 
						 type:@"" actor:[amazon getActors] 
					     summary:@"" comment:@""
						 tags:@"" path:[amazon getImageData]];
	[[NSNotificationCenter defaultCenter] postNotificationName:kHelloDataSourceDidChangeNotification object:nil];
	[self closeAddPanel:sender];
}

- (IBAction) closeButton:(id)sender
{
	[self closeAddPanel:sender];
}

- (void) closeAddPanel:(id)sender
{
	[title_add setStringValue:@""]; 
	[NSApp endSheet:add_panel];
	[add_panel orderOut:sender];
}

- (IBAction) removeItem:(id)sender
{
	int						index = 0;
	
	if ([switch_button selectedSegment] == 1)
		index = [[[viewControllers objectAtIndex:1] tableView] selectedRow];
	else
		index = [[[[viewControllers objectAtIndex:0] DvdGrid] selectionIndexes] firstIndex];
		
	[dvd_list removeItemAtIndex:index];
	[[NSNotificationCenter defaultCenter] postNotificationName:kHelloDataSourceDidChangeNotification object:nil];

	 [panel close];
}

- (void)changePanelValue:(NSDictionary*)item
{	
	[title_field setStringValue:[item objectForKey:kTitle]];
	[director_field setStringValue:[item objectForKey:kDirector]];
	[year_field setStringValue:[item objectForKey:kYear]];
	[type_field setStringValue:[item objectForKey:kType]];
	[comment_field setStringValue:[item objectForKey:kComment]];
	[tags_field setStringValue:[item objectForKey:kTags]];
	[language_field setStringValue:[item objectForKey:kLanguage]];
	[actor_field setStringValue:[item objectForKey:kActor]];
	[summary_field setStringValue:[item objectForKey:kSummary]];
}

- (void) dataSourceDidChange:(NSNotificationCenter*)notification
{
	if ([switch_button selectedSegment] == 1)
		[[[viewControllers objectAtIndex:1] tableView] reloadData];
	else
		[[[viewControllers objectAtIndex:0] DvdGrid] reloadData];
}

- (void) mode_edit
{
	[title_field setEditable:false];
	[director_field setEditable:false];
	[year_field setEditable:false];
	[type_field setEditable:false];
	[comment_field setEditable:false];
	[tags_field setEditable:false];	
	[language_field setEditable:false];
	[actor_field setEditable:false];
	[summary_field setEditable:false];
	
	[comment_field setBezeled:false];
	[title_field setBezeled:false];
	[director_field setBezeled:false];
	[year_field setBezeled:false];
	[type_field setBezeled:false];
	[comment_field setBezeled:false];
	[tags_field setBezeled:false];
	[language_field setBezeled:false];
	[actor_field setBezeled:false];
	[summary_field setBezeled:false];
	
	[title_field setSelectable:false];
	[director_field setSelectable:false];
	[year_field setSelectable:false];
	[type_field setSelectable:false];
	[comment_field setSelectable:false];
	[language_field setSelectable:false];
	[actor_field setSelectable:false];
	[summary_field setSelectable:false];

	[path setHidden:YES];
	
	[edit setTitle:@"Edit"];
}

- (void) mode_save
{
	[title_field setEditable:true];
	[director_field setEditable:true];
	[year_field setEditable:true];
	[type_field setEditable:true];
	[comment_field setEditable:true];
	[tags_field setEditable:true];
	[language_field setEditable:true];
	[actor_field setEditable:true];
	[summary_field setEditable:true];
	
	[title_field setSelectable:true];
	[director_field setSelectable:true];
	[year_field setSelectable:true];
	[type_field setSelectable:true];
	[comment_field setSelectable:true];
	[tags_field setSelectable:true];
	[language_field setSelectable:true];
	[actor_field setSelectable:true];
	[summary_field setSelectable:true];
	
	[title_field setBezeled:true];
	[director_field setBezeled:true];
	[year_field setBezeled:true];
	[type_field setBezeled:true];
	[comment_field setBezeled:true];
	[tags_field setBezeled:true];
	[language_field setBezeled:true];
	[actor_field setBezeled:true];
	[summary_field setBezeled:true];

	[path setHidden:NO];
	
	[edit setTitle:@"Save"];
}

- (void)controlTextDidChange:(NSNotification *)aNotification
{
	if ([[title_add stringValue] isEqualToString:@""])
		[addDvdButton setEnabled:NO];
	else
		[addDvdButton setEnabled:YES];
}

- (void)tableViewSelection:(NSNotification *)aNotification
{
	int				index = [[[viewControllers objectAtIndex:1] tableView] selectedRow];

	if (index == -1)
	{
		[self mode_edit];
		[panel close];
	}
	else
	{
		[panel open];
		[self displayImage:[dvd_list itemAtIndex:index]];
		[panel setMaxContentSize:NSSizeFromString(@"{400,400}")];
		[panel setContentSize:NSSizeFromString(@"{400,400}")];
		[self changePanelValue:[dvd_list itemAtIndex:index]];
	}
}

- (IBAction) edit_mode:(id) sender
{
	int					index = 0;
	NSDictionary		*dvd = [NSDictionary alloc];
	
	if ([switch_button selectedSegment] == 0)
		index = [[[[viewControllers objectAtIndex:0] DvdGrid] selectionIndexes] firstIndex];
	else
		index = [[[viewControllers objectAtIndex:1] tableView] selectedRow];
	
	if ([[edit title] isEqualToString:@"Edit"])
	{
		[self mode_save];
	}
	else
	{ 
		dvd = [NSDictionary	dictionaryWithObjectsAndKeys:[[dvd_list itemAtIndex:index] objectForKey:kId], kId,
														[title_field stringValue], kTitle, [director_field stringValue], kDirector, 
			                                            [language_field stringValue], kLanguage, [year_field stringValue], kYear,
														[type_field stringValue], kType, [actor_field stringValue], kActor, 
														[summary_field stringValue], kSummary, [comment_field stringValue], kComment, 
														[tags_field stringValue], kTags, [[dvd_list itemAtIndex:index] objectForKey:kPath], kPath, nil];
		[dvd_list changeDvdAtIndex:index item:dvd];
		[[NSNotificationCenter defaultCenter] postNotificationName:kHelloDataSourceDidChangeNotification object:nil];
		[self displayImage:[dvd_list itemAtIndex:index]];
		[self mode_edit];
	}
}

- (IBAction)updateFilter:sender
{		
	NSString 	*search_string = [search_field stringValue];
	NSPredicate *regextest = nil;
	
	if ((search_string != nil) && (![search_string isEqualToString:@""]))
	{
		if (searchCategory == 0)
			regextest = [NSPredicate predicateWithFormat:@"((%K CONTAINS[cd] %@) || (%K CONTAINS[cd] %@) || (%K CONTAINS[cd] %@) || \
						 (%K CONTAINS[cd] %@) || (%K CONTAINS[cd] %@) || (%K CONTAINS[cd] %@) || (%K CONTAINS[cd] %@) || (%K CONTAINS[cd] %@) || \
						 (%K CONTAINS[cd] %@) || (%K CONTAINS[cd] %@))", kTitle, search_string, kDirector, search_string, kYear,
						 search_string, kLanguage, search_string, kType, search_string, kActor, search_string, kSummary, search_string,
						 kSummary, search_string, kComment, search_string, kTags, search_string];
		if (searchCategory == 1)
			regextest = [NSPredicate predicateWithFormat:@"(%K CONTAINS[cd] %@)", kTitle, search_string];
		if (searchCategory == 2)
			regextest = [NSPredicate predicateWithFormat:@"(%K CONTAINS[cd] %@)", kDirector, search_string];
		if (searchCategory == 3)
			regextest = [NSPredicate predicateWithFormat:@"(%K CONTAINS[cd] %@)", kYear, search_string];
		if (searchCategory == 4)
			regextest = [NSPredicate predicateWithFormat:@"(%K CONTAINS[cd] %@)", kType, search_string];
		if (searchCategory == 5)
			regextest = [NSPredicate predicateWithFormat:@"(%K CONTAINS[cd] %@)", kSummary, search_string];
		[dvd_list updatewithPredicate:regextest];
	}
	else
		[dvd_list reinitialize];
	[[NSNotificationCenter defaultCenter] postNotificationName:kHelloDataSourceDidChangeNotification object:nil];
}

- (IBAction)		openAmazonPanel:(id)sender
{
	if (!amazonPanel)
		amazonPanel = [[AmazonCall alloc] initWithWindowNibName:@"AmazonWindow"];
	[amazonPanel showWindow:self];
}

- (void)showPreferences:(id)sender
{
	[[MBPreferencesController sharedController] showWindow:sender];
}

- (void) displayImage:(NSDictionary*)item
{
	NSImage		*img;
		
	if ([[item objectForKey:kPath] hasPrefix:@"http:"] == NO)
	{
		NSLog(@"ne match pas\n");
		img = [[NSImage alloc] initWithContentsOfFile:[item objectForKey:kPath]];
	}
	else
	{
		NSLog(@"%@\n", [item objectForKey:kPath]);
		img = [[NSImage alloc] initWithContentsOfURL:[NSURL URLWithString:[item objectForKey:kPath]]];
		NSLog(@"match\n");
	}
	if ([picture image]!=nil)
		[[picture image] release];
	[picture setImage:img];
	[picture setNeedsDisplay:YES];
}

- (IBAction) choosefile:(id)sender
{
	
	NSOpenPanel* oPanel = [NSOpenPanel openPanel];
	int			i = 0;
	NSArray *fileTypes = [NSArray arrayWithObjects:@"jpg", @"gif",@"png", @"psd", @"tga", nil];
	
	[oPanel setCanChooseDirectories:NO];		// Disable the selection of directories in the dialog.
	[oPanel setCanChooseFiles:YES];				// Enable the selection of files in the dialog.
	[oPanel setCanCreateDirectories:YES];		// Enable the creation of directories in the dialog
	[oPanel setAllowsMultipleSelection:NO];		// Allow multiple files selection
	[oPanel setAlphaValue:0.95];				// Alpha value
	[oPanel setTitle:@"Select a file to open"];
	if ([oPanel runModalForDirectory:nil file:nil types:fileTypes] == NSOKButton)
	{
		NSArray* files = [oPanel filenames];
		for(i = 0; i < [files count]; i++)
		{
			//NSMutableString *part = [[NSMutableString alloc] initWithString:@"http://"];
			NSString* fileName = [files objectAtIndex:i];
			NSLog (fileName);
			//[part appendFormat:@"%@", fileName];
			//fileName = part;
			int					index = 0;
			if ([switch_button selectedSegment] == 0)
				index = [[[[viewControllers objectAtIndex:0] DvdGrid] selectionIndexes] firstIndex];
			else
				index = [[[viewControllers objectAtIndex:1] tableView] selectedRow];
			
			NSDictionary		*dvd = [NSDictionary alloc];
			dvd = [NSDictionary	dictionaryWithObjectsAndKeys:[[dvd_list itemAtIndex:index] objectForKey:kId], kId,
				   [[dvd_list itemAtIndex:index] objectForKey:kTitle], kTitle, 
				   [[dvd_list itemAtIndex:index] objectForKey:kDirector], kDirector, 
				   [[dvd_list itemAtIndex:index] objectForKey:kLanguage], kLanguage, 
				   [[dvd_list itemAtIndex:index] objectForKey:kYear], kYear,
				   [[dvd_list itemAtIndex:index] objectForKey:kType], kType, 
				   [[dvd_list itemAtIndex:index] objectForKey:kActor], kActor, 
				   [[dvd_list itemAtIndex:index] objectForKey:kSummary], kSummary, 
				   [[dvd_list itemAtIndex:index] objectForKey:kComment], kComment, 
				   [[dvd_list itemAtIndex:index] objectForKey:kTags], kTags, 
				   fileName, kPath, nil];
			[dvd_list changeDvdAtIndex:index item:dvd];
			[self displayImage:[dvd_list itemAtIndex:index]];
			[[NSNotificationCenter defaultCenter] postNotificationName:kHelloDataSourceDidChangeNotification object:nil];
		}
	}
}

- (IBAction)addSheet:(id)sender {

	[NSApp beginSheet:add_panel
	   modalForWindow:mainWindow
		modalDelegate:self
	   didEndSelector:NULL
		  contextInfo:NULL];
}

- (IBAction)exportDataBase:(id)sender
{
	NSSavePanel *save = [NSSavePanel savePanel];
	[save setRequiredFileType:@"xml"];
	int result = [save runModal];
	if (result == NSOKButton)
	{
		NSString *selectedFile = [save filename];
		NSFileManager *fileManager = [NSFileManager defaultManager];
		NSString *dataBaseFile = [[[[NSHomeDirectory()
								   stringByAppendingPathComponent:@"Library"]
								  stringByAppendingPathComponent:@"Application Support"]
								 stringByAppendingPathComponent:@"Rainbow"]
								 stringByAppendingPathComponent:@"DvdList.xml"];
		if ([fileManager fileExistsAtPath:dataBaseFile])
		{
			[fileManager copyPath:dataBaseFile
						   toPath:selectedFile
						  handler:nil];
			NSLog(@"Database succesfully exported");
		}
		else
			NSLog(@"Tried to export the database file, but it doesn't exist!");
	}
}

- (IBAction)importDataBase:(id)sender
{
	NSOpenPanel *open = [NSOpenPanel openPanel];
	int result = [open runModal];
	if (result == NSOKButton)
	{
		NSString *selectedFile = [open filename];
		NSFileManager *fileManager = [NSFileManager defaultManager];

		NSString *dataBaseFile = [[[[NSHomeDirectory()
									 stringByAppendingPathComponent:@"Library"]
									stringByAppendingPathComponent:@"Application Support"]
								   stringByAppendingPathComponent:@"Rainbow"]
								  stringByAppendingPathComponent:@"DvdList.xml"];

		if ([fileManager removeFileAtPath:dataBaseFile handler:nil])
		{
			NSLog(@"Current database removed");
		
			if ([fileManager copyPath:selectedFile
							   toPath:dataBaseFile
							  handler:nil])
			{
				NSLog(@"Database succesfully imported");
				dvd_list = [[Dvd alloc] init];
				[[NSNotificationCenter defaultCenter] postNotificationName:kHelloDataSourceDidChangeNotification object:nil];
			}
		}
	}
}

- (NSUInteger) numberOfItemsInImageBrowser:(IKImageBrowserView *)aBrowser
{
	return [dvd_list count];
}

- (id) imageBrowser:(IKImageBrowserView *)aBrowser itemAtIndex:(NSUInteger)index
{
	
	NSImage		*img;
	NSDictionary *dico = [[NSDictionary alloc] init];
	
	dico = [dvd_list itemAtIndex:index];
	
	if ([[dico objectForKey:kPath] hasPrefix:@"http:"] == NO)
		img = [[NSImage alloc] initWithContentsOfFile:[dico objectForKey:kPath]];
	else
		img = [[NSImage alloc] initWithContentsOfURL:[NSURL URLWithString:[dico objectForKey:kPath]]];
	itemGridDVD *item = NULL;
		item = [[itemGridDVD alloc] initWithImage:img 
											title:[[dvd_list itemAtIndex:index] objectForKey:kTitle] 
										 director:[[dvd_list itemAtIndex:index] objectForKey:kDirector]
											   Id:[[dvd_list itemAtIndex:index] objectForKey:kId]];
	return item;
	
}

- (void) imageBrowser:(IKImageBrowserView *) aBrowser removeItemsAtIndexes:(NSIndexSet *) indexes
{
	for (int i = [indexes firstIndex]; i < [indexes lastIndex]; i++)
		[dvd_list removeItemAtIndex:i];
}

- (void) gridNoSelection:(NSNotification*)notification
{
	[panel close];
}

- (void) gridSelectionDidChange:(NSNotification *)notification
{
	NSInteger			index = [[[[viewControllers objectAtIndex:0] DvdGrid] selectionIndexes] firstIndex];

	if (index == -1)
	{
		[self mode_edit];
		[panel close];
	}
	else
	{
		[panel open];
		[panel setMaxContentSize:NSSizeFromString(@"{400,400}")];
		[panel setContentSize:NSSizeFromString(@"{400,400}")];
		[self displayImage:[dvd_list itemAtIndex:index]];
		[self changePanelValue:[dvd_list itemAtIndex:index]];
	}
}

//functions to have the swapping view mode

- (void) displayViewController:(ManagingViewController *)vc
{
	NSWindow *w = [box window];
	BOOL ended = [w makeFirstResponder:w];
	if (!ended)
	{
		NSBeep();
		return;
	}
	NSView *v = [vc view];
	[box setContentView:v];
}

- (IBAction) changeViewContoller:(id)sender
{
	ManagingViewController *vc = [viewControllers objectAtIndex:[switch_button selectedSegment]];
	if ([switch_button selectedSegment] == 0)
		[slideBar setHidden:NO];
	else
		[slideBar setHidden:YES];
	[self displayViewController:vc];
	[[NSNotificationCenter defaultCenter] postNotificationName:kHelloDataSourceDidChangeNotification object:nil];
}

- (IBAction) zoomSliderDidChange:(id)sender
{
	[[[viewControllers objectAtIndex:0] DvdGrid] setZoomValue:[sender floatValue]];
    [[[viewControllers objectAtIndex:0] DvdGrid] setNeedsDisplay:YES];
}

- (void) dealloc
{
	[viewControllers release];
	[dvd_list release];
	[tv release];
	[amazonPanel release];
	[super dealloc];
}

@end
